<template>
  <div class="app-container">
    <ContentWrap>
      <el-row :gutter="20">
        <el-col :span="8" class="content-container">
          <div style="width: 100%;height: 40px;line-height: 20px;display: flex;align-items: baseline;justify-content: space-between;">
            <div>压差报警</div>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="openDialog">异常压差表配置</el-button>
          </div>
          <el-table v-loading="setLoading" :data="setList" border size="mini" :height="getLeftHeight"
            highlight-current-row @current-change="handleCurrentChange">
            <el-table-column label="设备A" width="100" align="center" prop="terminalNameOne" fixed/>
            <el-table-column label="设备B" width="100" align="center" prop="terminalNameTwo" fixed/>
            <el-table-column label="压差" width="60" align="center" prop="value" fixed/>
            <el-table-column label="开始时间" width="135" align="center" prop="startTime"/>
            <el-table-column label="结束时间" width="135" align="center" prop="endTime"/>
            <el-table-column label="压差标准值" width="60" align="center" prop="standardPressure"/>
          </el-table>
        </el-col>
        <el-col :span="16" class="content-container">
          <el-row :style="'height: '+getRightHeight+'px;'">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
              <el-form-item label="设备" prop="terminalIds">
                <el-select v-model="queryParams.terminalIds" multiple placeholder="请选择" size="small" filterable collapse-tags :multiple-limit="2">
                  <el-option v-for="item in terminalList" :key="item.terminalID" :label="item.terminalName" :value="item.terminalID"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker style="width: 190px;" v-model="queryParams.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker style="width: 190px;" v-model="queryParams.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item>               
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <!-- 表格 -->
              <!-- A表名称，B表名称，A表压力，B表压力，AB压力差，时间点  -->
            <el-table v-loading="loading" :data="dataList" border size="mini" :height="getAvailableHeight">
              <el-table-column type="index" width="35" align="center" label="#"/>
              <el-table-column label="设备A" min-width="150" align="center" prop="terminalName1" />
              <el-table-column label="设备A压力" min-width="80" align="center" prop="pressure1" />
              <el-table-column label="设备B" min-width="150" align="center" prop="terminalName2" />
              <el-table-column label="设备B压力" min-width="80" align="center" prop="pressure2" />
              <el-table-column label="压力差" min-width="120" align="center" prop="value"/>
              <el-table-column label="数据时间" min-width="120" align="center" prop="dataTime"/>       
            </el-table>
            <pagination :total="total"
                        :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getDataList"
                        size="mini"
                        layout="total, prev, pager, next, jumper"/>
          </el-row>
          <el-row :style="'height: '+getRightHeight+'px;'">
            <div class="chart-container" style="height: 100%;width: 100%;">
              <div id="chart" style="height: 100%;width: 100%;">

              </div>
            </div>
          </el-row>
        </el-col>
      </el-row>


      <!-- 配置 -->
      <el-dialog :title="setTitle" :visible.sync="setOpen" width="720px" append-to-body>
        <el-form ref="setForm" size="small" :inline="true" label-width="68px">
          <el-form-item>               
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="setAdd">新增</el-button>
            <el-button icon="el-icon-delete" size="mini" @click="setDelete">删除</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="configLoading" :data="configDataList" border size="mini" :height="getAvailableHeight" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="设备A" min-width="150" align="center" prop="terminalName1" />
          <el-table-column label="设备B" min-width="150" align="center" prop="terminalName2" />
          <el-table-column label="压差标准值" min-width="120" align="center" prop="standardPressure"/>
        </el-table>

        <!-- 新增多表压差配置 -->
        <el-dialog :title="subTitle" :visible.sync="subOpen" width="350px" append-to-body>
          <el-form :model="configForm" ref="configForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="设备A" prop="terminalIdOne">
              <el-select v-model="configForm.terminalIdOne" placeholder="请选择" size="small">
                <el-option v-for="item in terminalList" :key="item.terminalID" :label="item.terminalName" :value="item.terminalID"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备B" prop="terminalIdTwo">
              <el-select v-model="configForm.terminalIdTwo" placeholder="请选择" size="small">
                <el-option v-for="item in terminalList" :key="item.terminalID" :label="item.terminalName" :value="item.terminalID"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="压差标准值" prop="standardPressure">
              <el-input v-model="configForm.standardPressure" placeholder="请输入压差标准值" clearable />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

      </el-dialog>
      <!-- <Locator :dialogShow.sync="siteDialog" @locationSure="locationSure" :primitiveData="primitiveData"></Locator> -->
    </ContentWrap>
  </div>
</template>

<script>
import moment from 'moment'
import CustomDialog from '@/views/leakage/components/CustomDialog.vue';
import {listAllTerminals} from "@/api/leakage/terminalsInfo";
import {getMultiTerminalDataList,getMultiTerminalDataChart} from "@/api/leakage/terminalHistoryData";
import {listConfig,addConfig,delConfig} from "@/api/leakage/pressureConfiguration";
import {getMultiWarnlist} from "@/api/leakage/warnss";
import * as echarts from 'echarts';

require('echarts/theme/macarons') // echarts theme
export default {
  name: 'multiMonitor',
  dicts: ['warn_handle_status', 'warn_param_type', 'warn_target_type', 'warn_status', 'warn_type'],
  components: { CustomDialog },
  data() {
    return {
      screenHeight: null,
      setLoading:false,
      setList:[
      
      ],
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        terminalIds: null,
        startTime:'',
        endTime: '',
      },
      dataList: [],
      terminalList:[],
      chart:undefined,
      baseOption: {
        legend: {
          data: ['设备A压力 MPa','设备B压力 MPa']
        },
        grid: {
          top: '5%',
          right: '5%',
          bottom: 65,
          left: '6%',
          containsLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        dataZoom: [{
          "show": true,
          "height": 30,
          "xAxisIndex": [
            0
          ],
          bottom: 5,
          "start": 10,
          "end": 80,
          handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
          handleSize: '110%',
          handleStyle: {
            color: "#d3dee5",
          },
          textStyle: {
            color: "#fff"
          },
          borderColor: "#90979c"
        }, {
          "type": "inside",
          "show": true,
          "height": 15,
          "start": 1,
          "end": 35
        }],
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: [
          {
            type: 'value',
            // position: 'right',
            axisLine: {
              show: true,
            },
            axisLabel: {
              formatter: '{value} MPa'
            }
          }
        ],
        series: [
          {
            name: '设备A压力 MPa',
            data: [],
            type: 'line',
            smooth: true
          },
          {
            name: '设备B压力 MPa',
            data: [],
            type: 'line',
            smooth: true,
            // yAxisIndex: 1
          }
        ]
      },
      chartData:{},
      //弹框
      setTitle:'异常压差表配置',
      setOpen:false,
      subTitle:'新增',
      subOpen:false,
      configLoading:false,
      configDataList:[],
      selecteConfigIds:[],
      configForm:{},
    }
  },
  methods: {
    //打开新增配置弹框
    setAdd(){
      this.subOpen = true;
    },
    //删除配置
    setDelete(){
      let that = this;
      this.$modal.confirm('是否确认删除多表压差配置？').then(function () {  
        return delConfig(that.selecteConfigIds.join(","));
      }).then(() => {
        this.getConfigDataList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["configForm"].validate(valid => {
        if (valid) {
            addConfig(this.configForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.subOpen = false;
              this.reset();
              this.getConfigDataList();
            });
        }
      });
    },
    handleSelectionChange(e) {
      this.selecteConfigIds = e.map(item => item.id);
    },
    getConfigDataList() {
      this.configLoading = true;
      listConfig({}).then(res => {
        let arrData = res.data;
        if(arrData.length>0){
          let dd = this.getTerminalMap(this.terminalList);
          arrData.forEach(item => {
            let one = dd.get(item.terminalIdOne);
            let two = dd.get(item.terminalIdTwo);
            item.terminalName1 = one ? one[0].terminalName : "";
            item.terminalName2 = two ? two[0].terminalName : "";
          });
          this.configDataList = arrData;
        }
        this.configLoading = false;
      });
    },
    getTerminalMap(arr){
      return arr.reduce((map, item) => {
            const { terminalID } = item;
            if (!map.has(terminalID)) {
              map.set(terminalID, []);
            }
            map.get(terminalID).push(item);
            return map;
          }, new Map());
    },
    // 取消按钮
    cancel() {
      this.subOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.configForm = {
        id: null,
        terminalIdOne:null,
        terminalIdTwo:null,
        standardPressure:null,
      };
      this.resetForm("configForm");
    },
    //打开弹框
    openDialog() {
      this.setOpen = true;
      this.getConfigDataList();
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('chart'), 'macarons')
    },
    initTerminals(){
      listAllTerminals({CurrentPressure:1}).then(res => {
        this.terminalList = res.data;
      });
    },
    updateOption(data) {
      const xAxisData = data.timeList.map(item => {
        const m = new moment(item)
        return m.format('MM-DD HH:mm')
      })
      const option = Object.assign({}, this.baseOption)
      option.xAxis.data = xAxisData
      option.series[0].data = data.pressList1
      option.series[1].data = data.pressList2
      this.chart.setOption(option)
    },
    handleCurrentChange(v) {
      //赋值查询条件
       Object.assign(this.queryParams,{
        terminalIds:[v.terminalIdOne,v.terminalIdTwo],
        startTime:v.startTime,
        endTime:v.endTime      
       });
       //查询
       this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getDataList();
      this.getChartList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getDataList() {
      this.loading = true;
      getMultiTerminalDataList(this.queryParams).then(res => {
        this.dataList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    getChartList() {
      getMultiTerminalDataChart(this.queryParams).then(res => {
        this.chartData = res.data;
        this.updateOption(this.chartData);
      });
    },
    getWarnSsDataList() {
      this.setLoading = true;
      getMultiWarnlist({}).then(res => {
        this.setList = res.data;
        this.setLoading = false;
      });
    },
  },
  created() {
    this.screenHeight = document.body.clientHeight;
    this.initTerminals();
  },
  computed: {
    getLeftHeight() {
      return this.screenHeight - 162;
    },
    getAvailableHeight() {
      return (this.screenHeight - 162)/2 - 100;
    },
    getRightHeight(){
      return (this.screenHeight - 122)/2;
    },
    getAvailableHeight1() {
      return (this.screenHeight - 48)/2;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
      this.getWarnSsDataList();
    })
    window.onresize = () => {
      this.screenHeight = document.body.clientHeight
    }
  }
}

</script>

<style scoped lang="scss">
.option-tool {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
// .el-select .el-tag{
//   max-width: 72% !important;
// }
</style>
